package com.example.content.activity

import android.content.Intent
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.donkingliang.imageselector.utils.ImageSelector
import com.example.content.DEFAULT_ITEM_TYPE
import com.example.content.R
import com.example.content.SELECT_TYPE
import com.example.content.VIDEO_URL
import com.example.content.adapter.recycle.BindListener
import com.example.content.adapter.recycle.RecyclerAdapter
import com.example.content.adapter.recycle.entity.ItemEntity
import com.example.content.databinding.UploadPhotosLayoutBinding
import com.example.content.manager.GlideEngine
import com.example.content.manager.GlobalMgr
import com.example.content.viewmodule.login.TokenStore
import com.example.content.viewmodule.product.UpProductViewModel
import com.example.core.extensions.showToast
import com.huantansheng.easyphotos.EasyPhotos
import com.huantansheng.easyphotos.constant.Type
import com.huantansheng.easyphotos.models.album.entity.Photo
import com.huantansheng.easyphotos.setting.Setting
import com.huantansheng.easyphotos.utils.file.FileUtils
import com.huantansheng.easyphotos.utils.media.DurationUtils
import com.huantansheng.easyphotos.utils.uri.UriUtils
import com.xuexiang.xui.utils.WidgetUtils
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog
import java.io.File
import java.util.*

class UpProductActivity : BaseActivity<UploadPhotosLayoutBinding, UpProductViewModel>(),
    View.OnClickListener {
    val footItemType = 51
    private lateinit var photosAdapter: RecyclerAdapter<Photo>
    private val footItem = ItemEntity(footItemType, Photo("", null,"",0,0,0,0,0,""))
    private var selectType = 2
    private lateinit var loadingDialog:MiniLoadingDialog

    //保存已选中的图片
    private val imageSelected = mutableListOf<Photo>()
    override fun initData() {
        photosAdapter = RecyclerAdapter(object : BindListener<Photo> {
            override fun convert(holder: BaseViewHolder, item: ItemEntity<Photo>) {
                when (holder.itemViewType) {
                    DEFAULT_ITEM_TYPE -> {
                        val image = holder.getView<ImageView>(R.id.image)
//                        if (selectType == 2) {
//                            Glide.with(this@UpProductActivity).load(item.data.path).into(image)
//                        } else {
                        Glide.with(this@UpProductActivity).load(item.data.uri).into(image)
//                        }
                        val delete = holder.getView<View>(R.id.delete)
                        Log.e("xxxduration", "convert: time: " + item.data.duration)
                        val videoTime = holder.getView<TextView>(R.id.tv_type)
                        if (selectType == 1) {
                            videoTime.visibility = View.VISIBLE
                            videoTime.text = DurationUtils.format(item.data.duration)
                        } else {
                            videoTime.visibility = View.GONE
                        }
                        delete.setOnClickListener {
                            if (imageSelected.size > holder.layoutPosition) {
                                photosAdapter.data.removeAt(holder.layoutPosition)
                                imageSelected.removeAt(holder.layoutPosition)
                                photosAdapter.notifyDataSetChanged()
                            }
                        }
                    }
                    footItemType -> {
                        val image = holder.getView<ImageView>(R.id.image)
                        image.setImageResource(R.drawable.ic_add)
                        val deleteImage = holder.getView<View>(R.id.delete)
                        deleteImage.visibility = View.GONE
                    }
                }
            }
        })
        photosAdapter.addItemView(R.layout.item_upload_image_layout)
        photosAdapter.addItemViewByType(footItemType, R.layout.item_upload_image_layout)

        val imageDatas = intent.getParcelableArrayListExtra<Photo>(EasyPhotos.RESULT_PHOTOS)
        selectType = intent.getIntExtra(SELECT_TYPE, 2)
        val videoUrl = intent.getStringExtra(VIDEO_URL)
        if (selectType == 1 && videoUrl != null && videoUrl.isNotBlank()) {
            val file = File(videoUrl)
            val uri = FileUtils.getUri(file)
            val photo = Photo(file.name, uri, videoUrl, 0, 0, 0, 0, 0, "")
            photosAdapter.data.clear()
            photosAdapter.addData(ItemEntity(data = photo))
            imageSelected.add(photo)
        } else if (imageDatas != null) {
            for (image in imageDatas) {
                photosAdapter.addData(ItemEntity(data = image))
            }
            imageSelected.addAll(imageDatas)
        }
        photosAdapter.addData(footItem)
        val layoutManager = GridLayoutManager(this, 3)
        dataBinding.recyclerView.layoutManager = layoutManager
        dataBinding.recyclerView.adapter = photosAdapter
    }

    override fun initView() {
        loadingDialog = MiniLoadingDialog(this, "上传中...")
    }

    override fun initListener() {
        dataBinding.backIcon.setOnClickListener(this)
        photosAdapter.setOnItemClickListener { adapter, view, position ->
            if (adapter.getItemViewType(position) == footItemType) {
                if (selectType == 2) {
                    EasyPhotos.createAlbum(this, true, GlideEngine)
                        .setFileProviderAuthority("com.example.pvshow.fileprovider")
                        .setCameraLocation(Setting.LIST_FIRST)
                        .setCount(9)
                        .setSelectedPhotos(imageSelected as ArrayList<Photo>?)
                        .start(REQUEST_CODE)
                } else {
                    EasyPhotos.createAlbum(this, true, GlideEngine)
                        .setFileProviderAuthority("com.example.pvshow.fileprovider")
                        .setCount(1)
                        .filter(Type.VIDEO)
                        .start(REQUEST_CODE)
                }
            } else {
                // TODO: 2020/12/8 点击查看图片大图
            }
        }
        dataBinding.uploadProduct.setOnClickListener {
            val msg = dataBinding.uploadMsg.text.toString()

            val urls = mutableListOf<String>()
            for (url in imageSelected) {
                urls.add(url.path)
            }

            // TODO: 3/9/21 参数分离
            if (imageSelected.size > 0) {
                loadingDialog.show()
                viewModel.uploadPhotos(msg, urls, selectType, TokenStore.sexyType)
            }
        }
        viewModel.resultData.observe(this, observer = {
            if (it.code == 200) {
                showToast("上传成功")
                GlobalMgr.uploadProduct.postValue(true)
                finish()
            }
            loadingDialog.hide()
        })

        viewModel.percentData.observe(this, {
            Log.e("jianting", "initListener: " + it)
            if (loadingDialog != null) {
                loadingDialog.setTitle("上传中...(${it})")
            }
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE && data != null) {
            val images = data.getParcelableArrayListExtra<Photo>(EasyPhotos.RESULT_PHOTOS)
            photosAdapter.data.clear()
            images?.forEach {
                photosAdapter.addData(ItemEntity(data = it))
            }
            imageSelected.clear()
            imageSelected.addAll(images)
            if (images.size < 10) {
                photosAdapter.addData(footItem)
            }
            photosAdapter.notifyDataSetChanged()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        loadingDialog.recycle()
    }

    override fun getLayoutId() = R.layout.upload_photos_layout
    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.back_icon -> {
                finish()
            }
            R.id.upload_product -> {

            }
        }
    }

    companion object {
        const val REQUEST_CODE = 10001
    }
}